package cn.com.header.zbpk.weixin.controller;


import cn.com.header.core.util.HttpJsonUtil;
import cn.com.header.core.util.weixin.CheckUtil;
import cn.com.header.core.util.weixin.WeixinUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("wechat")
public class WeixinController {

    /**
     * 校验信息是否是从微信服务器发过来的。
     *
     * @param
     * @param out
     */
    @RequestMapping(method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    public void valid(HttpServletRequest request, PrintWriter out) {
        System.out.println("进来了");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");


        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        } else {
            System.out.println("不是微信服务器发来的请求,请小心!");
        }
        out.flush();
        out.close();
    }
    /**
     * 微信消息的处理
     *
     * @param request
     * @param
     * @throws IOException
     */
    @RequestMapping(method = {RequestMethod.POST}, produces = "application/xml;charset=UTF-8")
    public void dispose(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        /* 消息的接收、处理、响应 */

        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 调用核心业务类接收消息、处理消息
            /*String respMessage = CoreService.processRequest(request);
            log.info(respMessage);*/
        // 响应消息
        PrintWriter out = response.getWriter();
        out.print("");
        out.close();
    }

    @RequestMapping(value = "/redirect", method = RequestMethod.GET)
    public String weixinRedirect(HttpServletRequest request, HttpServletResponse response) {
        String url= "http://fengnuoyang.tunnel.echomod.cn/wechat/oauth";
        return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeixinUtil.APPID+"&redirect_uri="+url+"?response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect";
}

    @RequestMapping(value = "/oauth", method = RequestMethod.GET)
    public String weixinOAuth(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        //得到code
        String CODE = request.getParameter("code");
        System.out.println(CODE+"_--------------");
        String APPID =WeixinUtil.APPID;
        String SECRET =WeixinUtil.APPSECRET;
        //换取access_token 其中包含了openid
        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code".replace("APPID", APPID).replace("SECRET", SECRET).replace("CODE", CODE);
        //发送请求获取openId
        JSONObject jsonObj= HttpJsonUtil.doGetStr(URL);
        System.out.println(jsonObj.toString());
        //out.print(jsonStr);
        String openid = jsonObj.get("openid").toString();
        request.setAttribute("openId",openid);
        //有了用户的opendi就可以的到用户的信息了
        //地址为https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        //得到用户信息之后返回到一个页面
        System.out.println("微信openid："+openid);
        return "weixinOk";
    }
}

